//
//  NSString+YJURL.m
//  YJExtensionDemo
//
//  Created by cool on 2018/6/11.
//  Copyright © 2018 child. All rights reserved.
//

#import "NSString+YJURL.h"

@implementation NSString (YJURL)

- (NSDictionary *)yj_URLParse {
    if (self == nil || self.length <= 0) { return @{}; }
    NSString *text = self;
    if (![text containsString:@"?"]) {
        text = [@"?" stringByAppendingString:text];
    }
    NSMutableDictionary *muDict = [NSMutableDictionary dictionary];
    NSURLComponents *components = [[NSURLComponents alloc] initWithString:text];
    for (NSURLQueryItem *item in components.queryItems) {
        if (item.name) {
            [muDict setObject:item.value forKey:item.name];
        }
    }
    return muDict.copy;
}

- (NSString *)yj_addParameters:(NSDictionary *)parameters
{
    NSString *paramterString = @"";
    for (NSString *key in parameters) {
        if (paramterString.length > 0) {
            paramterString = [paramterString stringByAppendingString:@"&"];
        }
        paramterString = [paramterString stringByAppendingFormat:@"%@=%@", key, [parameters valueForKey:key]];
    }
    if (paramterString.length == 0) {
        return self;
    }
    if ([self rangeOfString:@"?"].location == NSNotFound) {
        return [self stringByAppendingFormat:@"?%@", paramterString];
    } else if ([[self substringWithRange:(NSRange){self.length -1, 1}] isEqualToString:@"?"]) {
        return [self stringByAppendingString:paramterString];
    }
    return [self stringByAppendingFormat:@"&%@", paramterString];
}

@end
